import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User } from '@/types/user'
import { authAPI } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isAuthenticated = ref(false)

  const init = () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
      loadUserInfo()
    }
  }

  const login = async (username: string, password: string) => {
    const response = await authAPI.login({ usernameOrEmail: username, password })
    token.value = response.token
    user.value = response.user
    isAuthenticated.value = true
    
    localStorage.setItem('token', response.token)
  }

  const logout = () => {
    user.value = null
    token.value = null
    isAuthenticated.value = false
    localStorage.removeItem('token')
  }

  const loadUserInfo = async () => {
    try {
      const userData = await authAPI.getCurrentUser()
      user.value = userData
      isAuthenticated.value = true
    } catch (error) {
      logout()
    }
  }

  return {
    user,
    token,
    isAuthenticated,
    init,
    login,
    logout,
    loadUserInfo
  }
})
